package com.tarena.lbs.user.service.impl;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.encoder.JwtEncoder;
import com.tarena.lbs.user.dao.repository.AdminRepository;
import com.tarena.lbs.user.pojo.param.AdminLoginParam;
import com.tarena.lbs.user.pojo.po.AdminPO;
import com.tarena.lbs.user.pojo.vo.LoginVO;
import com.tarena.lbs.user.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    AdminRepository adminRepository;

    @Autowired
    private JwtEncoder<Map<String, Object>> jwtEncoder;

    @Override
    public LoginVO adminLogin(AdminLoginParam param) throws BusinessException {
        log.info("serviceimpl 管理员登录：{}"+param);
        // 1. 根据手机号查询用户
        AdminPO adminPO = adminRepository.findByPhone(param.getPhone());
        if (adminPO == null) {
            throw new BusinessException("1", "用户不存在");
        }

        // 2. 校验密码 (MD5加密后比较)
//        String encryptedPassword = DigestUtils.md5DigestAsHex(param.getPassword().getBytes());
        if (!param.getPassword().equals(adminPO.getAccountPassword())) {
            throw new BusinessException("1", "密码错误");
        }

        // 3. 准备JWT payload数据
        Map<String, Object> payload = new HashMap<>();
        payload.put("id", adminPO.getId());
        payload.put("accountType", adminPO.getAccountType());
        payload.put("nickname", adminPO.getNickname());

        // 4. 生成JWT token
        String token = jwtEncoder.generateToken(payload);

        // 5. 返回登录结果
        return new LoginVO(
                token,
                adminPO.getId(),
                adminPO.getNickname()
        );
    }
}